package com.jn.algorithm.day001.question2;

/**
 * @author 江南大学1033190417
 * @date 2022/4/15 10:36
 */
public class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;//进位
        ListNode a = l1, b = l2, p = null;
        while (a != null || b != null) {
            int val = (a == null ? 0 : a.val) + (b == null ? 0 : b.val) + carry;
            carry = val > 9 ? 1 : 0;
            val = val % 10;
            p = a == null ? b : a;
            p.val = val;
            //a,b都前进一位
            a = a == null ? null : a.next;
            b = b == null ? null : b.next;

            p.next = a == null ? b : a;
        }
        if (carry > 0) {
            p.next = new ListNode(1);
        }
        return l1;
    }

    public ListNode mySolution(ListNode l1, ListNode l2) {
        ListNode a = l1, b = l2, p = null;
        int carry = 0;//进位
        while (a != null || b != null) {
            int val = (a==null?0:a.val) + (b==null?0:b.val + carry);
            carry = val >= 10 ? 1 : 0;
            val = val % 10;
            p = a == null ? b : a;
            p.val=val;

            //a,b都前进
            a=a==null?null:a.next;
            b=b==null?null:b.next;

            //p也要根据a/b指定next
            p.next=a==null?b:a;
        }
        if (carry>0){
            p.next=new ListNode(1);
        }
        return l1;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode();
        l1.val = 9;

        ListNode l2 = new ListNode();
        l2.val = 9;
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);
        l2.next.next.next = new ListNode(9);
        l2.next.next.next.next = new ListNode(9);
        l2.next.next.next.next.next = new ListNode(9);
        l2.next.next.next.next.next.next = new ListNode(9);
        l2.next.next.next.next.next.next.next = new ListNode(9);
        l2.next.next.next.next.next.next.next.next = new ListNode(9);
        l2.next.next.next.next.next.next.next.next.next = new ListNode(1);

        Solution2 solution = new Solution2();
        ListNode listNode = solution.mySolution(l1, l2);
        while (listNode != null) {
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }
}


